package services

import (
	"errors"
	"server/app/common/request"
	"server/app/models"
	"server/global"
	"server/utils"
	"strconv"
	"time"

	"gorm.io/gorm"
)

type userService struct{}

var UserService = new(userService)

func (userService *userService) Register(params request.Register) (err error, user models.Users) {
	if global.App.DB == nil {
		return errors.New("数据库未连接.."), user
	}
	var result = global.App.DB.Where("mobile=?", params.Mobile).Select("id").First(&models.Users{}) //没连接数据库会报错，gorm.where报空指针
	if result.RowsAffected != 0 {
		err = errors.New("手机号已存在")
		return
	}
	user = models.Users{Name: params.Name, Mobile: params.Mobile, Password: utils.BcryptMake([]byte(params.Password))}
	err = global.App.DB.Create(&user).Error
	return
}

// Login登录
func (userService *userService) Login(params request.Login) (err error, user *models.Users) {
	if global.App.DB == nil {
		return errors.New("数据库未连接"), user
	}
	//尝试查找用户
	result := global.App.DB.Where("mobile=?", params.Mobile).First(&user)

	//找不到就注册
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		//此处可添加更多的用户信息
		user = &models.Users{Name: params.Name, Mobile: params.Mobile, Password: utils.BcryptMake([]byte(params.Password))}
		err = global.App.DB.Create(&user).Error
		if err != nil {
			return errors.New("注册失败"), user
		}
		//新用户初始化逻辑
	} else if result.Error != nil {
		//数据库查询错误
		return errors.New("数据库查询错误"), user
	} else {
		//用户存在，检查密码
		if !utils.BcryptMakeCheck([]byte(params.Password), user.Password) {
			return errors.New("密码错误"), user
		}
	}
	//记录登录
	if err := UserService.RecordLogin(user, params.IP, params.UserAgent); err != nil {
		return errors.New("登录记录失败"), user
	}
	return nil, user
	/* 	纯登录逻辑
	err = global.App.DB.Where("mobile=?", params.Mobile).First(&user).Error
	if err != nil || !utils.BcryptMakeCheck([]byte(params.Password), user.Password) {
		err = errors.New("用户名不存在或密码错误")
		return
	}
	if err := UserService.RecordLogin(user, params.IP, params.UserAgent); err != nil {
		err = errors.New("无法存入登录记录")
	}
	return
	*/
}

// 登录记录
func (userService *userService) RecordLogin(user *models.Users, ip string, userAgent string) error {
	if global.App.DB == nil {
		return errors.New("数据库未连接..")
	}
	record := models.LoginRecords{
		UserID:    user.ID.ID,
		LoginTime: time.Now(),
		IP:        ip,
		UserAgent: userAgent,
	}

	err := global.App.DB.Create(&record).Error
	return err
}

// GetUserInfo获取用户信息
func (userService *userService) GetUserInfo(id string) (err error, user models.Users) {
	intId, _ := strconv.Atoi(id)
	err = global.App.DB.First(&user, intId).Error
	if err != nil {
		err = errors.New("数据不存在")
	}
	return
}

// 设置用户信息
func (userService *userService) SetUserInfo(id string, form request.UserInfo) (err error) {
	intId, err := strconv.Atoi(id)
	if err != nil {
		return
	}
	err = global.App.DB.Model(models.Users{}).Where("id = ? ", intId).Updates(models.Users{
		Name: form.Name,
	}).Error

	if err != nil {
		return
	}

	return
}
